package com.zyx.resolver;

import com.zyx.anno.CurrentUser;
import com.zyx.context.BaseContextHandler;
import com.zyx.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * <p>自定义参数解析器
 *
 * @author Yaxi.Zhang
 * @since 2022/10/7 10:38
 */
public class CurrentUserMethodArgumentResolver  implements HandlerMethodArgumentResolver {

    public CurrentUserMethodArgumentResolver() {
        System.out.println("CurrentUserMethodArgumentResolver自定义参数解析器初始化...");
    }

    @Override
    public boolean supportsParameter(@NonNull MethodParameter parameter) {
        // 如果Controller的方法参数类型为User同时还加入了CurrentUser注解，则返回true
        return parameter.getParameterType().equals(User.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        System.out.println("参数解析器...");
        // 此处直接模拟了一个User对象，实际项目中可能需要从请求头中获取登录用户的令牌然后进行解析
        return new User(BaseContextHandler.getUserId(),BaseContextHandler.getUserName());
    }
}
